#-*- coding:UTF-8 -*-
'''
Copyright 2009 http://code.google.com/p/mygaepy/. All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
  * Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.
  * Redistributions in binary form must reproduce the above
    copyright notice, this list of conditions and the following
    disclaimer in the documentation and/or other materials provided
    with the distribution.
  * Neither the name of http://code.google.com/p/mygaepy/ nor the names of its
    contributors may be used to endorse or promote products derived
    from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''

import logging
import time
import os
from datetime import date

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from pygments import highlight
from pygments.formatters import HtmlFormatter
from pygments.lexers import get_lexer_by_name

from models import *
from methods import *
import settings
from BaseHandler import BaseRequestHandler

def codehighlight(code, lang):
	try:
		lexer=get_lexer_by_name(lang)
	except Exception,msg:
		logging.warning(msg)
		lexer=get_lexer_by_name('text')
	return highlight(code, lexer, HtmlFormatter(noclasses=True))

class BlogList(BaseRequestHandler):
    """
    show a list of blogs
    """
    def get(self, page=0):
    	self.init()
    	self.template_v["isblog"]=True
    	page = int(page)
    	limit = 10
    	if page < 0:
    		page=0
    	entries = getBlogs(page, limit)
    	if len(entries) == limit:
    		self.template_v["showolder"] = True
    	else:
    		self.template_v["showolder"] = False
    	self.template_v["entries"] = entries
    	self.template_v["pageindex"] = page
    	path = os.path.join(os.path.dirname(__file__), 'templates/blog/list.html')
    	self.response.out.write(template.render(path,self.template_v))
    
    def post(self, page):
    	self.get(page)
    	
class BlogPost(BaseRequestHandler):
    def get(self):
    	self.init()
    	self.template_v["isblog"]=True
        path = os.path.join(os.path.dirname(__file__), 'templates/blog/post.html')
        self.response.out.write(template.render(path,self.template_v))
    def post(self):
    	self.init()
    	self.template_v["isblog"]=True
        title = self.request.get("title","").strip()
        blogtags = self.request.get("tags","").strip()
        content = self.request.get("content")
        if title=="":
        	self.template_v["content"] = content
        	self.template_v["blogtags"] = blogtags
        	path = os.path.join(os.path.dirname(__file__), 'templates/blog/post.html')
        	self.response.out.write(template.render(path,self.template_v))
        else:
        	blogtags = blogtags.split()
        	tagsset = set(blogtags)
        	blogtags = list(tagsset)
        	blog = Blog()
        	bid = getNextBlogId()
        	blog.bid = bid
        	blog.title = title
        	blog.times = 0
        	blog.content = content
        	blog.tags = blogtags
        	blog.put()
        	bloginfo = Bloginfo(bid, title, blog.pubday)
        	for t in blogtags:
        		setTag(t, bid, bloginfo)
        	year = date.today().year
        	month = date.today().month
        	setArchieve(year, month, bloginfo)
        	sys = getSysInfo()
        	sys.blognum += 1
        	sys.save()
        	self.redirect("/blog")

class BlogEdit(BaseRequestHandler):
    def get(self, id):
    	self.init()
    	self.template_v["isblog"]=True
    	id = int(id)
    	blog = getBlogById(id)
    	if blog:
    		self.template_v["title"]=blog.title
    		self.template_v["content"]=blog.content
    		self.template_v["blogtags"]=" ".join(blog.tags)
    		self.template_v["bid"]=blog.bid
    		self.template_v["auth"]=setBlogEditAuth(id)
    		path = os.path.join(os.path.dirname(__file__), 'templates/blog/edit.html')
    		self.response.out.write(template.render(path,self.template_v))

    def post(self, bid):
    	self.init()
    	self.template_v["isblog"]=True
        title = self.request.get("title","").strip()
        blogtags = self.request.get("tags","").strip()
        content = self.request.get("content","")
        bid=int(bid)
        auth=self.request.get("auth","")
        if title=="":
        	self.template_v["content"] = content
        	self.template_v["blogtags"] = blogtags
        	path = os.path.join(os.path.dirname(__file__), 'templates/blog/post.html')
        	self.response.out.write(template.render(path,self.template_v))
        else:
        	blogtags = blogtags.split()
        	tagsset = set(blogtags)
        	blogtags = list(tagsset)        	
        	blog = getBlogById(bid)
        	blog.title = title
        	blog.content = content
        	oldtags = blog.tags
        	#delete old tags
        	for t in oldtags:
        		deleteTag(t,bid)
        	#update new tags
        	bloginfo = Bloginfo(bid, title, blog.pubday)
        	for t in blogtags:
        		setTag(t,bid,bloginfo)
        	blog.tags = blogtags
        	blog.save()
        	self.redirect("/blog")

class BlogGet(BaseRequestHandler):
    def get(self,id = 1):
    	self.init()
    	self.template_v["isblog"]=True
    	id = int(id)
    	blog = getBlogById(id)
    	blog.times += 1
    	blog.save()
    	self.template_v["entry"] = blog
    	path = os.path.join(os.path.dirname(__file__), 'templates/blog/get.html')
    	self.response.out.write(template.render(path,self.template_v))

class BlogDelete(BaseRequestHandler):
    def get(self,id):
    	self.init()
    	self.template_v["isblog"]=True
    	id = int(id)
    	blog = getBlogById(id)
    	try:
    		year = blog.pubday.year
    		month = blog.pubday.month
    		delArchieve(year, month, id)
    		for t in blog.tags:
    			deleteTag(t, blog.bid)
    		blog.remove()
    		#reset tag info
    		sysinfo = getSysInfo()
    		sysinfo.blognum -= 1
    		sysinfo.save()
    		self.redirect("/blog")
    	except Exception, message:
    		self.showerrorpage(message)

class BlogMonth(BaseRequestHandler):
    def get(self, month):
    	self.init()
    	self.template_v["isblog"]=True
    	try:
    		year,month=month.split("-")
    	except:
    		year=date.today().year
    		month=date.today().month
    	year=int(year)
    	month=int(month)
        entries = getBlogByMonth(year,month)
        self.template_v["entries"]=entries
        path = os.path.join(os.path.dirname(__file__), 'templates/blog/list.html')
        self.response.out.write(template.render(path,self.template_v))

class BlogCodeBeaty(webapp.RequestHandler):
	def post(self):
		self.get()
	def get(self):
		code = self.request.get("code","")
		lang = self.request.get("lang","")
		str=codehighlight(code,lang)
		self.response.out.write(str)

def main():
	application = webapp.WSGIApplication([
										('/blog/list/?', BlogList),
										('/blog/list/(\d+)', BlogList),
										('/blog/post', BlogPost),
										('/blog/edit/(\d+)', BlogEdit),
										('/blog/get/(.*)', BlogGet),
										('/blog/delete/(.*)', BlogDelete),
										('/blog/month/(.*)', BlogMonth),
										('/blog/cb',BlogCodeBeaty),
										('/blog/?', BlogList),
										])
	run_wsgi_app(application)

if __name__ == '__main__':
	main()